package com.qixin.modules.rzInvoice.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.qixin.modules.eaBasic.util.ChangeIdToNameUtil;
import com.qixin.modules.eaBasic.util.MapUtil;
import com.qixin.modules.rzInvoice.entity.*;
import com.qixin.modules.rzInvoice.mapper.EaBillItemMapper;
import com.qixin.modules.rzInvoice.service.*;
import com.qixin.modules.rzInvoice.vo.EaBillPage;
import com.qixin.utils.FastDFSClient;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.fapiao.glority.GlorityService;
import org.jeecg.common.util.CommonUtils;
import org.jeecg.common.util.DateFormatUtil;
import org.jeecg.common.util.EmptyUtil;
import org.jeecg.common.util.oConvertUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@Api(tags = "发票识别操作类")
@RestController
@RequestMapping("/ocr/invoice")
@Slf4j
public class InvoiceController {

    @Value(value = "${jeecg.path.upload}")
    private String uploadpath;

    /**
     * 本地：local minio：minio 阿里：alioss
     */
    @Value(value = "${jeecg.uploadType}")
    private String uploadType;

    @Value("${sever.servlet.context-path}")
    private String contextPath;

    /**
     * 增值税服务头表接口
     */
    @Autowired
    private IEaRzZzsService eaRzZzsService;
    /**
     * 增值税服务子表接口
     */
    @Autowired
    private IEaRzZzsItemsService eaRzZzsItemsService;
    /**
     * 增值税普通发票（卷票）接口
     */
    @Autowired
    private IEaRzZzsptfpService eaRzZzsptfpService;

    /**
     * 增值税普通发票（卷票）子表接口
     */
    @Autowired
    private IEaRzZzsptfpItemsService eaRzZzsptfpItemsService;

    /**
     * 火车票发票
     */
    @Autowired
    private IEaRzHcpService eaRzHcpService;
    /**
     * 出租车发票
     */
    @Autowired
    private IEaRzCzcService eaRzCzcService;
    /**
     * 可报销其他发票
     */
    @Autowired
    private IEaRzQtService eaRzQtService;
    /**
     * 定额发票
     */
    @Autowired
    private IEaRzDefpService eaRzDefpService;

    /**
     * 二手车统一销售发票
     */
    @Autowired
    private IEaRzEscxstyfpService eaRzEscxstyfpService;

    /**
     * 过路费发票
     */
    @Autowired
    private IEaRzGlfService eaRzGlfService;
    /**
     *
     * 机打发票 客运汽车票
     */
    @Autowired
    private IEaRzKyqcfpService eaRzKyqcfpService;

    /**
     * 航空运输电子客运行程单
     */
    @Autowired
    private IEaRzHkysdzkpxcdService eaRzHkysdzkpxcdService;


    /**
     * 船票
     */
    @Autowired
    private IEaRzCpService eaRzCpService;
    /**
     * 机动车销售统一发票
     */
    @Autowired
    private IEaRzJdcxstyfpService eaRzJdcxstyfpService;
    /**
     * 增值税专用发票
     */
    @Autowired
    private IEaRzZzszyfpService eaRzZzszyfpService;
    /**
     * 增值税电子普通发票
     */
    @Autowired
    private IEaRzZzsdzptfpService eaRzZzsdzptfpService;

    /**
     * 国际小票
     */
    @Autowired
    private IEaRzXpService eaRzXpService;
    /**
     * 完税证明发票
     */
    @Autowired
    private IEaRzWszmfpService eaRzWszmfpService;
    /**
     * 滴滴出行行程单
     */
    @Autowired
    private IEaRzDdcxxcdService eaRzDdcxxcdService;

    @Autowired
    private FastDFSClient fastDFSClient;

    @Autowired
    private ChangeIdToNameUtil changeIdToNameUtil;
    @Autowired
    private EaBillItemMapper eaBillItemMapper;

    /**
     * 发票识别-单张
     *
     * @return
     */
    @AutoLog(value = "发票识别-测试")
    @ApiOperation(value = "发票识别-测试", notes = "发票识别-测试")
    @PostMapping(value = "/test")
    public Result<?> test(HttpServletRequest request) {
        Result<?> result = new Result<>();
        String res = "{\"result\":1,\"response\":{\"data\":{\"version\":\"20210701\",\"result\":1,\"timestamp\":1625673835,\"message\":\"success\",\"id\":\"1ebf1238883580ac7aca825321326b22\",\"sha1\":\"be7e76ce84a07959fd3996b63ab073d877750b99\",\"time_cost\":\"561\",\"identify_results\":[{\"type\":\"10101\",\"orientation\":0,\"details\":{\"code\":\"035002000104\",\"number\":\"04114375\",\"date\":\"2021\\u5e7405\\u670806\\u65e5\",\"pretax_amount\":\"99.01\",\"tax\":\"0.99\",\"check_code\":\"04752747319193962050\",\"total\":\"100.00\",\"seller\":\"\\u798f\\u5dde\\u5e02\\u4ed3\\u5c71\\u533a\\u60a6\\u5ba2\\u697c\\u9910\\u996e\\u5e97\",\"seller_tax_id\":\"92350104MA34M1MK23\",\"buyer\":\"\\u798f\\u5efa\\u6d77\\u5ce1\\u519b\\u6c11\\u878d\\u5408\\u4ea7\\u4e1a\\u53d1\\u5c55\\u6709\\u9650\\u516c\\u53f8\",\"buyer_tax_id\":\"91350104MA33LG6952\",\"company_seal\":\"1\",\"form_type\":\"\\u7b2c\\u4e8c\\u8054\",\"form_name\":\"\\u53d1\\u7968\\u8054\",\"kind\":\"\\u9910\\u996e\",\"ciphertext\":\"00778-6>94+*>-23<4<4657*+1+4,07<1**60-3\\/*9+8<31+4+3*8349<,>21\\/664<<37+5\\/>378<18<\\/-9441,*5+7*52\\/8>>1<801197*06040<3\\/\",\"machine_code\":\"917002890355\",\"receiptor\":\"\",\"reviewer\":\"\",\"issuer\":\"\\u738b\\u4e3d\\u6587\",\"province\":\"\\u798f\\u5efa\\u7701\",\"city\":\"\",\"service_name\":\"\\u9910\\u996e\\u670d\\u52a1\",\"remark\":\"\",\"item_names\":\"*\\u9910\\u996e\\u670d\\u52a1*\\u9910\\u8d39\",\"items\":[{\"name\":\"*\\u9910\\u996e\\u670d\\u52a1*\\u9910\\u8d39\",\"total\":\"99.01\",\"tax_rate\":\"1%\",\"tax\":\"0\"}],\"code_confirm\":\"035002000\",\"number_confirm\":\"041143\",\"total_cn\":\"\\u58f9\\u4f70\\u5706\\u6574\"},\"extra\":{\"check_code_candidates\":[\"04752747319193962050\",\"04752747319193962056\"],\"check_code_last_six\":[\"962050\",\"962056\"],\"number_order_error\":[\"041143\"],\"qrcode\":[\"01,04,035002000104,04114375,99.01,20210506,04752747319193962050,4F1F,\"]}}]}}}";

        JSONObject jsonObject = JSON.parseObject(res);
        if (jsonObject.getIntValue("result") == 0) {
            System.out.println(res);
        }
        // 获取返回值，对返回值进行解析
        JSONObject rsdata = jsonObject.parseObject(jsonObject.getString("response")).getJSONObject("data");
        JSONArray identifyResults = rsdata.getJSONArray("identify_results");
        for (int idx = 0; idx < identifyResults.size(); idx++) {
            JSONObject rs = identifyResults.getJSONObject(idx);
            JSONObject data = rs.getJSONObject("details");
            if ("10101".equals(rs.getString("type"))) {
                // 增值税票
                EaRzZzs eaRzZzs = new EaRzZzs();
                eaRzZzs.setCode(data.getString("code"));
                eaRzZzs.setNumber(data.getString("number"));
                eaRzZzs.setDate(data.getString("date"));
                eaRzZzs.setPretaxAmount(data.getString("pretax_amount"));
                eaRzZzs.setTax(data.getString("tax"));
                eaRzZzs.setCheckCode(data.getString("check_code"));
                eaRzZzs.setTotal(data.getString("total"));
                eaRzZzs.setSeller(data.getString("seller"));
                eaRzZzs.setSellerTaxId(data.getString("seller_tax_id"));
                eaRzZzs.setBuyer(data.getString("buyer"));
                eaRzZzs.setBuyerTaxId(data.getString("91350103581114048G"));
                eaRzZzs.setCompanySeal(data.getString("company_seal"));
                eaRzZzs.setFormType(data.getString("form_type"));
                eaRzZzs.setFormName(data.getString("form_name"));
                eaRzZzs.setKind(data.getString("kind"));
                eaRzZzs.setCiphertext(data.getString("ciphertext"));
                eaRzZzs.setReceiptor(data.getString("receiptor"));
                eaRzZzs.setReviewer(data.getString("reviewer"));
                eaRzZzs.setIssuer(data.getString("issuer"));
                eaRzZzs.setProvince(data.getString("province"));
                eaRzZzs.setCity(data.getString("city"));
                eaRzZzs.setServiceName(data.getString("service_name"));
                eaRzZzs.setRemark(data.getString("remark"));
                eaRzZzs.setItemNames(data.getString("item_names"));
                eaRzZzs.setCodeConfirm(data.getString("code_confirm"));
                eaRzZzs.setNumberConfirn(data.getString("number_confirm"));
                eaRzZzs.setTotalCn(data.getString("total_cn"));
                JSONArray items = data.getJSONArray("items");
                List<EaRzZzsItems> eaRzZzsItemsList = new ArrayList<>();
                for (int i = 0; i < items.size(); i++) {
                    JSONObject item = items.getJSONObject(i);
                    EaRzZzsItems zzsItem = new EaRzZzsItems();
                    zzsItem.setName(item.getString("name"));
                    zzsItem.setTotal(item.getString("total"));
                    zzsItem.setTaxRate(item.getString("tax_rate"));
                    zzsItem.setTax(item.getString("tax"));
                    eaRzZzsItemsList.add(zzsItem);
                }
                // 保存到增值税发票表
                eaRzZzsService.saveMain(eaRzZzs, eaRzZzsItemsList);
            }
        }
        return result;
    }

    /**
     * 发票识别-单张
     *
     * @return
     */
    @AutoLog(value = "发票识别-单张")
    @ApiOperation(value = "发票识别-单张", notes = "发票识别-单张")
    @PostMapping(value = "/identify")
    public Result<?> identify(HttpServletRequest request) {
        Result<?> result = new Result<>();
        String savePath = "";
        String bizPath = request.getParameter("biz");
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile file = multipartRequest.getFile("file");// 获取上传文件对象
        if (null == file) {
            result.setMessage("文件不能为空！");
            result.setSuccess(false);
            return result;
        }

/*        if (oConvertUtils.isEmpty(bizPath)) {
            if (CommonConstant.UPLOAD_TYPE_OSS.equals(uploadType)) {
                //未指定目录，则用阿里云默认目录 upload
                bizPath = "upload";
            } else {
                bizPath = "";
            }
        }*/
        if (CommonConstant.UPLOAD_TYPE_LOCAL.equals(uploadType)) {
            //本地存储
            //savePath = this.uploadLocal(file,"");
            try {
                savePath = fastDFSClient.uploadFile(file);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (oConvertUtils.isNotEmpty(savePath)) {
            result.setMessage(savePath);
            result.setSuccess(true);
        } else {
            result.setMessage("上传失败！");
            result.setSuccess(false);
            return result;
        }

        // 调用发票识别接口- 校验发票
        try {
            // 取本地存储路径
            String ctxPath = uploadpath + File.separator + savePath;
            File ocrFile = new File(ctxPath);
            String res = GlorityService.getItemInfo(ocrFile);

            JSONObject jsonObject = JSON.parseObject(res);
            if (jsonObject.getIntValue("result") == 0) {
                result.setMessage("发票识别出现异常,错误信息：" + res);
                result.setSuccess(false);
                return result;
            }

            // 保存发票识别数据 --begin
            this.saveData(jsonObject,savePath);
            // 保存发票识别数据 --end
        }
        catch (Exception e) {
//        catch (IOException e) {
            e.printStackTrace();
            result.setMessage("调用发票识别接口出错！");
            result.setSuccess(false);
            return result;
        }
        return result;
    }

    /**
     * 保存发票数据
     * @param jsonObject 识别后的发票数据
     * @param savePath 发票保存路径
     */
    private void saveData(JSONObject jsonObject,String savePath){

        // 获取返回值，对返回值进行解析
        JSONObject rsdata = jsonObject.parseObject(jsonObject.getString("response")).getJSONObject("data");
        JSONArray identifyResults = rsdata.getJSONArray("identify_results");
        for (int idx = 0; idx < identifyResults.size(); idx++) {
            JSONObject rs = identifyResults.getJSONObject(idx);
            JSONObject data = rs.getJSONObject("details");
            String type = rs.getString("type");
            switch (type){
                case "10101":
                    // 增值税票
                    EaRzZzs eaRzZzs = new EaRzZzs();
                    eaRzZzs.setCode(data.getString("code"));
                    eaRzZzs.setNumber(data.getString("number"));
                    eaRzZzs.setDate(data.getString("date"));
                    eaRzZzs.setPretaxAmount(data.getString("pretax_amount"));
                    eaRzZzs.setTax(data.getString("tax"));
                    eaRzZzs.setCheckCode(data.getString("check_code"));
                    eaRzZzs.setTotal(data.getString("total"));
                    eaRzZzs.setSeller(data.getString("seller"));
                    eaRzZzs.setSellerTaxId(data.getString("seller_tax_id"));
                    eaRzZzs.setBuyer(data.getString("buyer"));
                    eaRzZzs.setBuyerTaxId(data.getString("91350103581114048G"));
                    eaRzZzs.setCompanySeal(data.getString("company_seal"));
                    eaRzZzs.setFormType(data.getString("form_type"));
                    eaRzZzs.setFormName(data.getString("form_name"));
                    eaRzZzs.setKind(data.getString("kind"));
                    eaRzZzs.setCiphertext(data.getString("ciphertext"));
                    eaRzZzs.setReceiptor(data.getString("receiptor"));
                    eaRzZzs.setReviewer(data.getString("reviewer"));
                    eaRzZzs.setIssuer(data.getString("issuer"));
                    eaRzZzs.setProvince(data.getString("province"));
                    eaRzZzs.setCity(data.getString("city"));
                    eaRzZzs.setServiceName(data.getString("service_name"));
                    eaRzZzs.setRemark(data.getString("remark"));
                    eaRzZzs.setItemNames(data.getString("item_names"));
                    eaRzZzs.setCodeConfirm(data.getString("code_confirm"));
                    eaRzZzs.setNumberConfirn(data.getString("number_confirm"));
                    eaRzZzs.setTotalCn(data.getString("total_cn"));
                    eaRzZzs.setInvoicePicUrl(savePath);
                    JSONArray zzsItems = data.getJSONArray("items");
                    List<EaRzZzsItems> eaRzZzsItemsList = new ArrayList<>();
                    for (int i = 0; i < zzsItems.size(); i++) {
                        JSONObject item = zzsItems.getJSONObject(i);
                        EaRzZzsItems zzsItem = new EaRzZzsItems();
                        zzsItem.setName(item.getString("name"));
                        zzsItem.setTotal(item.getString("total"));
                        zzsItem.setTaxRate(item.getString("tax_rate"));
                        zzsItem.setTax(item.getString("tax"));
                        eaRzZzsItemsList.add(zzsItem);
                    }
                    // 保存到增值税发票表
                    eaRzZzsService.saveMain(eaRzZzs, eaRzZzsItemsList);
                    break;
                case "10100":
                    //增值税专用发票
                    EaRzZzszyfp eaRzZzszyfp = new EaRzZzszyfp();
                    eaRzZzszyfp.setCode(data.getString("code"));
                    eaRzZzszyfp.setNumber(data.getString("number"));
                    eaRzZzszyfp.setDate(data.getString("date"));
                    eaRzZzszyfp.setPretaxAmount(data.getString("pretax_amount"));
                    eaRzZzszyfp.setTax(data.getString("tax"));
                    eaRzZzszyfp.setCheckCode(data.getString("check_code"));
                    eaRzZzszyfp.setTotal(data.getString("total"));
                    eaRzZzszyfp.setTotalCn(data.getString("total_cn"));
                    eaRzZzszyfp.setSeller(data.getString("seller"));
                    eaRzZzszyfp.setSellerTaxId(data.getString("seller_tax_id"));
                    eaRzZzszyfp.setBuyer(data.getString("buyer"));
                    eaRzZzszyfp.setBuyerTaxId(data.getString("buyer_tax_id"));
                    eaRzZzszyfp.setCompanySeal(data.getString("company_seal"));
                    eaRzZzszyfp.setFormType(data.getString("form_type"));
                    eaRzZzszyfp.setFormName(data.getString("form_name"));
                    eaRzZzszyfp.setKind(data.getString("kind"));
                    eaRzZzszyfp.setCiphertext(data.getString("ciphertext"));
                    eaRzZzszyfp.setReceiptor(data.getString("receiptor"));
                    eaRzZzszyfp.setReviewer(data.getString("reviewer"));
                    eaRzZzszyfp.setIssuer(data.getString("issuer"));
                    eaRzZzszyfp.setProvince(data.getString("province"));
                    eaRzZzszyfp.setCity(data.getString("city"));
                    eaRzZzszyfp.setServiceName(data.getString("service_name"));
                    eaRzZzszyfp.setRemark(data.getString("remark"));
                    eaRzZzszyfp.setItemNames(data.getString("item_names"));
                    eaRzZzszyfp.setCodeConfirm(data.getString("code_confirm"));
                    eaRzZzszyfp.setNumberConfirm(data.getString("number_confirm"));
                    eaRzZzszyfp.setElectronicMark(data.getString("electronic_mark"));
                    eaRzZzszyfp.setInvoicePicUrl(savePath);
                    JSONArray zzsZyItems = data.getJSONArray("items");
                    List<EaRzZzszyfpItems> eaRzZzszyfpList = new ArrayList<>();
                    for (int i = 0; i < zzsZyItems.size(); i++) {
                        JSONObject item = zzsZyItems.getJSONObject(i);
                        EaRzZzszyfpItems eaRzZzszyfpItems = new EaRzZzszyfpItems();
                        eaRzZzszyfpItems.setName(item.getString("name"));
                        eaRzZzszyfpItems.setQuantity(item.getString("quantity"));
                        eaRzZzszyfpItems.setPrice(item.getString("price"));
                        eaRzZzszyfpItems.setTotal(item.getString("total"));
                        eaRzZzszyfpItems.setTaxRate(item.getString("tax_rate"));
                        eaRzZzszyfpItems.setTax(item.getString("tax"));
                        eaRzZzszyfpList.add(eaRzZzszyfpItems);
                    }
                    eaRzZzszyfpService.saveMain(eaRzZzszyfp,eaRzZzszyfpList);
                    break;
                case "10102":
                    // 增值税电子普票
                    EaRzZzsdzptfp eaRzZzsdzptfp = new EaRzZzsdzptfp();
                    eaRzZzsdzptfp.setCode(data.getString("code"));
                    eaRzZzsdzptfp.setNumber(data.getString("number"));
                    eaRzZzsdzptfp.setDate(data.getString("date"));
                    eaRzZzsdzptfp.setPretaxAmount(data.getString("pretax_amount"));
                    eaRzZzsdzptfp.setTax(data.getString("tax"));
                    eaRzZzsdzptfp.setCheckCode(data.getString("check_code"));
                    eaRzZzsdzptfp.setTotal(data.getString("total"));
                    eaRzZzsdzptfp.setSeller(data.getString("seller"));
                    eaRzZzsdzptfp.setSellerTaxId(data.getString("seller_tax_id"));
                    eaRzZzsdzptfp.setBuyer(data.getString("buyer"));
                    eaRzZzsdzptfp.setBuyerTaxId(data.getString("buyer_tax_id"));
                    eaRzZzsdzptfp.setCompanySeal(data.getString("company_seal"));
                    eaRzZzsdzptfp.setFormType(data.getString("form_type"));
                    eaRzZzsdzptfp.setKind(data.getString("kind"));
                    eaRzZzsdzptfp.setCiphertext(data.getString("ciphertext"));
                    eaRzZzsdzptfp.setMachineCode(data.getString("machine_code"));
                    eaRzZzsdzptfp.setReceiptor(data.getString("receiptor"));
                    eaRzZzsdzptfp.setReviewer(data.getString("reviewer"));
                    eaRzZzsdzptfp.setIssuer(data.getString("issuer"));
                    eaRzZzsdzptfp.setProvince(data.getString("province"));
                    eaRzZzsdzptfp.setCity(data.getString("city"));
                    eaRzZzsdzptfp.setServiceName(data.getString("service_name"));
                    eaRzZzsdzptfp.setRemark(data.getString("remark"));
                    eaRzZzsdzptfp.setItemNames(data.getString("item_names"));
                    eaRzZzsdzptfp.setCodeConfirm(data.getString("code_confirm"));
                    eaRzZzsdzptfp.setElectronicMark(data.getString("electronic_mark"));
                    eaRzZzsdzptfp.setTotalCn(data.getString("total_cn"));
                    eaRzZzsdzptfp.setInvoicePicUrl(savePath);
                    JSONArray zzszdptItems = data.getJSONArray("items");
                    List<EaRzZzsdzptfpItems> eaRzZzsdzptfpItemsList = new ArrayList<>();
                    for (int i = 0; i < zzszdptItems.size(); i++) {
                        JSONObject item = zzszdptItems.getJSONObject(i);
                        EaRzZzsdzptfpItems eaRzZzsdzptfpItems = new EaRzZzsdzptfpItems();
                        eaRzZzsdzptfpItems.setName(item.getString("name"));
                        eaRzZzsdzptfpItems.setSpecification(item.getString("specification"));
                        eaRzZzsdzptfpItems.setUnit(item.getString("unit"));
                        eaRzZzsdzptfpItems.setQuantity(item.getString("quantity"));
                        eaRzZzsdzptfpItems.setPrice(item.getString("price"));
                        eaRzZzsdzptfpItems.setTotal(item.getString("total"));
                        eaRzZzsdzptfpItems.setTaxRate(item.getString("tax_rate"));
                        eaRzZzsdzptfpItems.setTax(item.getString("tax"));
                        eaRzZzsdzptfpItemsList.add(eaRzZzsdzptfpItems);
                    }
                    eaRzZzsdzptfpService.saveMain(eaRzZzsdzptfp,eaRzZzsdzptfpItemsList);
                    break;
                case "10103":
                    // 增值税普通发票(卷票)
                    EaRzZzsptfp eaRzZzsptfp = new EaRzZzsptfp();
                    eaRzZzsptfp.setCode(data.getString("code"));
                    eaRzZzsptfp.setNumber(data.getString("number"));
                    eaRzZzsptfp.setDate(data.getString("date"));
                    eaRzZzsptfp.setCheckCode(data.getString("check_code"));
                    eaRzZzsptfp.setSeller(data.getString("seller"));
                    eaRzZzsptfp.setSellerTaxId(data.getString("seller_tax_id"));
                    eaRzZzsptfp.setBuyer(data.getString("buyer"));
                    eaRzZzsptfp.setBuyerTaxId(data.getString("buyer_tax_id"));
                    eaRzZzsptfp.setTotal(data.getString("total"));
                    eaRzZzsptfp.setKind(data.getString("kind"));
                    eaRzZzsptfp.setProvince(data.getString("province"));
                    eaRzZzsptfp.setCity(data.getString("city"));
                    eaRzZzsptfp.setCompanySeal(data.getString("company_seal"));
                    eaRzZzsptfp.setServiceName(data.getString("service_name"));
                    eaRzZzsptfp.setItemNames(data.getString("item_names"));
                    eaRzZzsptfp.setInvoicePicUrl(savePath);
                    JSONArray zzsptItems = data.getJSONArray("items");
                    List<EaRzZzsptfpItems> eaRzZzsptfpItemsList = new ArrayList<>();
                    for (int i = 0; i < zzsptItems.size(); i++) {
                        JSONObject item = zzsptItems.getJSONObject(i);
                        EaRzZzsptfpItems zzsptfpItems = new EaRzZzsptfpItems();
                        zzsptfpItems.setName(item.getString("name"));
                        zzsptfpItems.setQuantity(item.getString("quantity"));
                        zzsptfpItems.setPrice(item.getString("price"));
                        zzsptfpItems.setTotal(item.getString("total"));
                        eaRzZzsptfpItemsList.add(zzsptfpItems);
                    }
                    eaRzZzsptfpService.saveMain(eaRzZzsptfp,eaRzZzsptfpItemsList);
                    break;
                case "10104":
                    // 机动车销售统一发票
                    EaRzJdcxstyfp eaRzJdcxstyfp = new EaRzJdcxstyfp();
                    eaRzJdcxstyfp.setCode(data.getString("code"));
                    eaRzJdcxstyfp.setNumber(data.getString("number"));
                    eaRzJdcxstyfp.setMachineCode(data.getString("machine_code"));
                    eaRzJdcxstyfp.setMachineNumber(data.getString("machine_number"));
                    eaRzJdcxstyfp.setDate(data.getString("date"));
                    eaRzJdcxstyfp.setPretaxAmount(data.getString("pretax_amount"));
                    eaRzJdcxstyfp.setTotal(data.getString("total"));
                    eaRzJdcxstyfp.setSeller(data.getString("seller"));
                    eaRzJdcxstyfp.setSellerTaxId(data.getString("seller_tax_id"));
                    eaRzJdcxstyfp.setBuyer(data.getString("buyer"));
                    eaRzJdcxstyfp.setBuyerId(data.getString("buyer_id"));
                    eaRzJdcxstyfp.setTaxAuthorities(data.getString("tax_authorities"));
                    eaRzJdcxstyfp.setTaxAuthoritiesCode(data.getString("tax_authorities_code"));
                    eaRzJdcxstyfp.setCarCode(data.getString("car_code"));
                    eaRzJdcxstyfp.setCarEngineCode(data.getString("car_engine_code"));
                    eaRzJdcxstyfp.setCarModel(data.getString("car_model"));
                    eaRzJdcxstyfp.setCertificateNumber(data.getString("certificate_number"));
                    eaRzJdcxstyfp.setKind(data.getString("kind"));
                    eaRzJdcxstyfp.setProvince(data.getString("province"));
                    eaRzJdcxstyfp.setCity(data.getString("city"));
                    eaRzJdcxstyfp.setTax(data.getString("tax"));
                    eaRzJdcxstyfp.setTaxRate(data.getString("tax_rate"));
                    eaRzJdcxstyfp.setCompanySeal(data.getString("company_seal"));
                    eaRzJdcxstyfp.setCarType(data.getString("car_type"));
                    eaRzJdcxstyfp.setAddress(data.getString("address"));
                    eaRzJdcxstyfp.setPhone(data.getString("phone"));
                    eaRzJdcxstyfp.setFormName(data.getString("form_name"));
                    eaRzJdcxstyfp.setFormType(data.getString("form_type"));
                    eaRzJdcxstyfp.setIssuer(data.getString("issuer"));
                    eaRzJdcxstyfp.setTaxNum(data.getString("tax_num"));
                    eaRzJdcxstyfp.setMaxPeopleNum(data.getString("max_people_num"));
                    eaRzJdcxstyfp.setOrigin(data.getString("origin"));
                    eaRzJdcxstyfp.setAccount(data.getString("account"));
                    eaRzJdcxstyfp.setInvoicePicUrl(savePath);
                    eaRzJdcxstyfpService.save(eaRzJdcxstyfp);
                    break;
                case "10105":
                    EaRzEscxstyfp eaRzEscxstyfp = new EaRzEscxstyfp();
                    eaRzEscxstyfp.setCode(data.getString("code"));
                    eaRzEscxstyfp.setNumber(data.getString("number"));
                    eaRzEscxstyfp.setDate(data.getString("date"));
                    eaRzEscxstyfp.setTotal(data.getString("total"));
                    eaRzEscxstyfp.setSeller(data.getString("seller"));
                    eaRzEscxstyfp.setSellerId(data.getString("seller_id"));
                    eaRzEscxstyfp.setBuyer(data.getString("buyer"));
                    eaRzEscxstyfp.setCompanyName(data.getString("company_name"));
                    eaRzEscxstyfp.setCompanyTaxId(data.getString("company_tax_id"));
                    eaRzEscxstyfp.setLicensePlate(data.getString("license_plate"));
                    eaRzEscxstyfp.setRegistrationNumber(data.getString("registration_number"));
                    eaRzEscxstyfp.setCarCode(data.getString("car_code"));
                    eaRzEscxstyfp.setCarModel(data.getString("car_model"));
                    eaRzEscxstyfp.setKind(data.getString("kind"));
                    eaRzEscxstyfp.setProvince(data.getString("province"));
                    eaRzEscxstyfp.setCity(data.getString("city"));
                    eaRzEscxstyfp.setCompanySeal(data.getString("company_seal"));
                    eaRzEscxstyfp.setBuyerAddress(data.getString("buyer_address"));
                    eaRzEscxstyfp.setSellerAddress(data.getString("seller_address"));
                    eaRzEscxstyfp.setCarType(data.getString("car_type"));
                    eaRzEscxstyfp.setCompanyBankAccount(data.getString("company_bank_account"));
                    eaRzEscxstyfp.setCompanyPhone(data.getString("company_phone"));
                    eaRzEscxstyfp.setFormName(data.getString("form_name"));
                    eaRzEscxstyfp.setFormType(data.getString("form_type"));
                    eaRzEscxstyfp.setCompanyAddress(data.getString("company_address"));
                    eaRzEscxstyfp.setInvoicePicUrl(savePath);
                    eaRzEscxstyfpService.save(eaRzEscxstyfp);
                    break;
                case "10200":
                    // 定额发票
                    EaRzDefp eaRzDefp = new EaRzDefp();
                    eaRzDefp.setCode(data.getString("code"));
                    eaRzDefp.setNumber(data.getString("number"));
                    eaRzDefp.setTotal(data.getString("total"));
                    eaRzDefp.setProvince(data.getString("province"));
                    eaRzDefp.setKind(data.getString("kind"));
                    eaRzDefp.setCity(data.getString("city"));
                    eaRzDefp.setCompanySeal(data.getString("company_seal"));
                    eaRzDefp.setInvoicePicUrl(savePath);
                    eaRzDefpService.save(eaRzDefp);
                    break;
                case "10500":
                    // 机打发票 出租车
                    EaRzCzc eaRzCzc = new EaRzCzc();
                    eaRzCzc.setCode(data.getString("code"));
                    eaRzCzc.setNumber(data.getString("number"));
                    eaRzCzc.setDate(data.getString("date"));
                    eaRzCzc.setMileage(data.getString("mileage"));
                    eaRzCzc.setTimeGeton(data.getString("time_geton"));
                    eaRzCzc.setTimeGetoff(data.getString("time_getoff"));
                    eaRzCzc.setTotal(data.getString("total"));
                    eaRzCzc.setPlace(data.getString("place"));
                    eaRzCzc.setKind(data.getString("kind"));
                    eaRzCzc.setProvince(data.getString("province"));
                    eaRzCzc.setCity(data.getString("city"));
                    eaRzCzc.setLicensePlate(data.getString("license_plate"));
                    eaRzCzc.setInvoicePicUrl(savePath);
                    eaRzCzcService.save(eaRzCzc);
                    break;
                case "10503":
                    // 火车票发票
                    EaRzHcp eaRzHcp = new EaRzHcp();
                    eaRzHcp.setNumber(data.getString("number"));
                    eaRzHcp.setDate(data.getString("date"));
                    eaRzHcp.setTime(data.getString("time"));
                    eaRzHcp.setName(data.getString("name"));
                    eaRzHcp.setStationGeton(data.getString("station_geton"));
                    eaRzHcp.setStationGetoff(data.getString("station_getoff"));
                    eaRzHcp.setTrainNumber(data.getString("train_number"));
                    eaRzHcp.setSeat(data.getString("seat"));
                    eaRzHcp.setTotal(data.getString("total"));
                    eaRzHcp.setKind(data.getString("kind"));
                    eaRzHcp.setSerialNumber(data.getString("serial_number"));
                    eaRzHcp.setUserId(data.getString("user_id"));
                    eaRzHcp.setInvoicePicUrl(savePath);
                    eaRzHcpService.save(eaRzHcp);
                    break;
                case "10505":
                    // 机打发票 客运汽车 （船票也会被识别成客运汽车票类型）
                    EaRzKyqcfp eaRzKyqcfp = new EaRzKyqcfp();
                    eaRzKyqcfp.setCode(data.getString("code"));
                    eaRzKyqcfp.setNumber(data.getString("number"));
                    eaRzKyqcfp.setDate(data.getString("date"));
                    eaRzKyqcfp.setTime(data.getString("time"));
                    eaRzKyqcfp.setStationGeton(data.getString("station_geton"));
                    eaRzKyqcfp.setStationGetoff(data.getString("station_getoff"));
                    eaRzKyqcfp.setTotal(data.getString("total"));
                    eaRzKyqcfp.setName(data.getString("name"));
                    eaRzKyqcfp.setKind(data.getString("kind"));
                    eaRzKyqcfp.setUserId(data.getString("user_id"));
                    eaRzKyqcfp.setInvoicePicUrl(savePath);
                    eaRzKyqcfpService.save(eaRzKyqcfp);
                    break;
                case "10506":
                    // 航空运输电子客票行程单
                    EaRzHkysdzkpxcd eaRzHkysdzkpxcd = new EaRzHkysdzkpxcd();
                    eaRzHkysdzkpxcd.setAgentcode(data.getString("agentcode"));
                    eaRzHkysdzkpxcd.setIssueBy(data.getString("issue_by"));
                    eaRzHkysdzkpxcd.setFare(data.getString("fare"));
                    eaRzHkysdzkpxcd.setTax(data.getString("tax"));
                    eaRzHkysdzkpxcd.setFuelSurcharge(data.getString("fuel_surcharge"));
                    eaRzHkysdzkpxcd.setCaacDevelopmentFund(data.getString("caac_development_fund"));
                    eaRzHkysdzkpxcd.setInsurance(data.getString("insurance"));
                    eaRzHkysdzkpxcd.setTotal(data.getString("total"));
                    eaRzHkysdzkpxcd.setInvoicePicUrl(savePath);
                    JSONArray items = data.getJSONArray("flights");
                    List<EaRzHkysdzkpxcdItems> eaRzHkysdzkpxcdItemsList = new ArrayList<>();
                    for (int i = 0; i < items.size(); i++) {
                        JSONObject item = items.getJSONObject(i);
                        EaRzHkysdzkpxcdItems eaRzHkysdzkpxcdItems = new EaRzHkysdzkpxcdItems();
                        eaRzHkysdzkpxcdItems.setFromStation(item.getString("from"));
                        eaRzHkysdzkpxcdItems.setToStation(item.getString("to"));
                        eaRzHkysdzkpxcdItems.setClassName(item.getString("class_name"));
                        eaRzHkysdzkpxcdItems.setFlightNumber(item.getString("flight_number"));
                        eaRzHkysdzkpxcdItems.setDate(item.getString("date"));
                        eaRzHkysdzkpxcdItems.setTime(item.getString("time"));
                        eaRzHkysdzkpxcdItems.setSeat(item.getString("seat"));
                        eaRzHkysdzkpxcdItems.setCarrier(item.getString("carrier"));
                        eaRzHkysdzkpxcdItems.setAllow(item.getString("allow"));
                        eaRzHkysdzkpxcdItemsList.add(eaRzHkysdzkpxcdItems);
                    }
                    eaRzHkysdzkpxcdService.saveMain(eaRzHkysdzkpxcd,eaRzHkysdzkpxcdItemsList);
                    break;
                case "10507":
                    // 过路费发票
                    EaRzGlf eaRzGlf = new EaRzGlf();
                    eaRzGlf.setCode(data.getString("code"));
                    eaRzGlf.setNumber(data.getString("number"));
                    eaRzGlf.setDate(data.getString("date"));
                    eaRzGlf.setTime(data.getString("time"));
                    eaRzGlf.setEntrance(data.getString("entrance"));
                    eaRzGlf.setExport(data.getString("exit"));
                    eaRzGlf.setTotal(data.getString("total"));
                    eaRzGlf.setKind(data.getString("kind"));
                    eaRzGlf.setHighwayFlag(data.getString("highway_flag"));
                    eaRzGlf.setInvoicePicUrl(savePath);
                    eaRzGlfService.save(eaRzGlf);
                    break;
                case "10900":
                    // 其他可报销发票
                    EaRzQt eaRzQt = new EaRzQt();
                    eaRzQt.setCode(data.getString("code"));
                    eaRzQt.setNumber(data.getString("number"));
                    eaRzQt.setDate(data.getString("date"));
                    eaRzQt.setTotal(data.getString("total"));
                    eaRzQt.setKind(data.getString("kind"));
                    eaRzQt.setInvoicePicUrl(savePath);
                    eaRzQtService.save(eaRzQt);
                    break;
                case "20100":
                    // 国际小票
                    EaRzXp eaRzXp = new EaRzXp();
                    eaRzXp.setStoreName(data.getString("store_name"));
                    eaRzXp.setDate(data.getString("date"));
                    eaRzXp.setTime(data.getString("time"));
                    eaRzXp.setSubtotal(data.getString("subtotal"));
                    eaRzXp.setTax(data.getString("tax"));
                    eaRzXp.setDiscount(data.getString("discount"));
                    eaRzXp.setTips(data.getString("tips"));
                    eaRzXp.setTotal(data.getString("total"));
                    eaRzXp.setCurrencyCode(data.getString("currency_code"));
                    eaRzXp.setType(data.getString("type"));
                    eaRzXp.setInvoicePicUrl(savePath);
                    eaRzXpService.save(eaRzXp);
                    break;
                case "20105":
                    // 滴滴出行行程单
                    EaRzDdcxxcd eaRzDdcxxcd = new EaRzDdcxxcd();
                    eaRzDdcxxcd.setDate(data.getString("date"));
                    eaRzDdcxxcd.setDateStart(data.getString("date_start"));
                    eaRzDdcxxcd.setDateEnd(data.getString("date_end"));
                    eaRzDdcxxcd.setPhone(data.getString("phone"));
                    eaRzDdcxxcd.setInvoicePicUrl(savePath);
                    JSONArray ddcxxcdItems = data.getJSONArray("items");
                    List<EaRzDdcxxcdItems> eaRzDdcxxcdItemsList = new ArrayList<>();
                    for (int i = 0; i < ddcxxcdItems.size(); i++) {
                        JSONObject item = ddcxxcdItems.getJSONObject(i);
                        EaRzDdcxxcdItems eaRzDdcxxcdItems = new EaRzDdcxxcdItems();
                        eaRzDdcxxcdItems.setCarType(item.getString("car_type"));
                        eaRzDdcxxcdItems.setTimeGeton(item.getString("time_geton"));
                        eaRzDdcxxcdItems.setCity(item.getString("city"));
                        eaRzDdcxxcdItems.setStationGeton(item.getString("station_geton"));
                        eaRzDdcxxcdItems.setStationGetoff(item.getString("station_getoff"));
                        eaRzDdcxxcdItems.setMileage(item.getString("mileage"));
                        eaRzDdcxxcdItems.setTotal(item.getString("total"));
                        eaRzDdcxxcdItemsList.add(eaRzDdcxxcdItems);
                    }
                    eaRzDdcxxcdService.saveMain(eaRzDdcxxcd,eaRzDdcxxcdItemsList);
                    break;
                default:
            }






        }
    }


    /**
     * 本地文件上传
     *
     * @param mf      文件
     * @param bizPath 自定义路径
     * @return
     */
    private String uploadLocal(MultipartFile mf, String bizPath) {
        try {
            String ctxPath = uploadpath;
            String fileName = null;
            File file = new File(ctxPath + File.separator + bizPath + File.separator);
            if (!file.exists()) {
                file.mkdirs();// 创建文件根目录
            }
            String orgName = mf.getOriginalFilename();// 获取文件名
            orgName = CommonUtils.getFileName(orgName);
            if (orgName.indexOf(".") != -1) {
                fileName = orgName.substring(0, orgName.lastIndexOf(".")) + "_" + System.currentTimeMillis() + orgName.substring(orgName.indexOf("."));
            } else {
                fileName = orgName + "_" + System.currentTimeMillis();
            }
            String savePath = file.getPath() + File.separator + fileName;
            File savefile = new File(savePath);
//            FileCopyUtils.copy(mf.getBytes(), savefile);
            FileUtils.copyInputStreamToFile(mf.getInputStream(),savefile);
            String dbpath = null;
            if (oConvertUtils.isNotEmpty(bizPath)) {
                dbpath = bizPath + File.separator + fileName;
            } else {
                dbpath = fileName;
            }
            if (dbpath.contains("\\")) {
                dbpath = dbpath.replace("\\", "/");
            }
            return dbpath;
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
        return "";
    }

    // MultipartFile 转 File
    private File transferToFile(MultipartFile multipartFile) {
//        选择用缓冲区来实现这个转换即使用java 创建的临时文件 使用 MultipartFile.transferto()方法 。
        File file = null;
        try {
            String originalFilename = multipartFile.getOriginalFilename();
            String[] filename = originalFilename.split("\\.");
            file = File.createTempFile(filename[0], filename[1]);
            multipartFile.transferTo(file);
            file.deleteOnExit();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file;
    }

}
